package com.dragon.aipictures.Controller;

import cn.hutool.core.util.ObjectUtil;
import com.dragon.aipictures.Exception.BusinessException;
import com.dragon.aipictures.Exception.StateCode;
import com.dragon.aipictures.annotation.AuthCheck;
import com.dragon.aipictures.common.BaseResponse;
import com.dragon.aipictures.constant.UserConstant;
import com.dragon.aipictures.domain.dto.request.spaceUser.SpaceUserAddRequest;
import com.dragon.aipictures.domain.dto.request.spaceUser.SpaceUserDeleteRequest;
import com.dragon.aipictures.domain.dto.request.spaceUser.SpaceUserEditRequest;
import com.dragon.aipictures.domain.dto.request.spaceUser.SpaceUserQueryRequest;
import com.dragon.aipictures.domain.entity.SpaceUser;
import com.dragon.aipictures.domain.entity.User;
import com.dragon.aipictures.domain.vo.spaceUser.SpaceUserVO;
import com.dragon.aipictures.manager.auth.annotation.SaSpaceCheckPermission;
import com.dragon.aipictures.manager.auth.model.SpaceUserPermissionConstant;
import com.dragon.aipictures.service.spaceUserService;
import com.dragon.aipictures.service.userService;
import com.dragon.aipictures.util.ResultUtils;
import com.dragon.aipictures.util.ThrowUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/spaceUser")
@Slf4j
public class SpaceUserController {

    @Resource
    private spaceUserService spaceUserService;

    @Resource
    private userService userService;

    /**
     * 添加成员到空间
     */
    @PostMapping("/add")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.SPACE_USER_MANAGE)
    public BaseResponse<Long> addSpaceUser(@RequestBody SpaceUserAddRequest spaceUserAddRequest, HttpServletRequest request) {
        ThrowUtil.throwIf(spaceUserAddRequest == null, StateCode.PARAMS_ERROR);
        long id = spaceUserService.addSpaceUser(spaceUserAddRequest);
        return ResultUtils.success(id);
    }

    /**
     * 从空间移除成员
     */
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.SPACE_USER_MANAGE)
    public BaseResponse<Boolean> deleteSpaceUser(@RequestBody SpaceUserDeleteRequest spaceUserDeleteRequest,
                                                 HttpServletRequest request) {
        if (spaceUserDeleteRequest == null ) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        Long id = spaceUserDeleteRequest.getId();
        if ((id == null) || (id <= 0)) {
            throw new BusinessException(StateCode.PARAMS_ERROR,"id不能为空且id不能小于等于0");
        }
        // 判断是否存在
        SpaceUser oldSpaceUser = spaceUserService.getById(id);
        ThrowUtil.throwIf(oldSpaceUser == null, StateCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = spaceUserService.removeById(id);
        ThrowUtil.throwIf(!result, StateCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 查询某个成员在某个空间的信息
     */
    @PostMapping("/get")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<SpaceUser> getSpaceUser(@RequestBody SpaceUserQueryRequest spaceUserQueryRequest) {
        // 参数校验
        ThrowUtil.throwIf(spaceUserQueryRequest == null, StateCode.PARAMS_ERROR);
        Long spaceId = spaceUserQueryRequest.getSpaceId();
        Long userId = spaceUserQueryRequest.getUserId();
        ThrowUtil.throwIf(ObjectUtil.hasEmpty(spaceId, userId), StateCode.PARAMS_ERROR);
        // 查询数据库
        SpaceUser spaceUser = spaceUserService.getOne(spaceUserService.getQueryWrapper(spaceUserQueryRequest));
        ThrowUtil.throwIf(spaceUser == null, StateCode.NOT_FOUND_ERROR);
        return ResultUtils.success(spaceUser);
    }

    /**
     * 查询成员信息列表
     */
    @PostMapping("/list/vo")
    //原代吗：必须是某个空间的管理员才可以查看该空间的成员信息列表,
    //本理解：但是其实只要是自己空间的成员信息，自己是可以查看到的
//    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.SPACE_USER_MANAGE)
    public BaseResponse<List<SpaceUserVO>> listSpaceUserVo(@RequestBody SpaceUserQueryRequest spaceUserQueryRequest,HttpServletRequest request) {
        ThrowUtil.throwIf(spaceUserQueryRequest == null, StateCode.PARAMS_ERROR);
        //用户必须指定查哪个空间的成员列表，管理员可以查全部
        Long spaceId = spaceUserQueryRequest.getSpaceId();
        ThrowUtil.throwIf(ObjectUtil.isEmpty(spaceId),StateCode.PARAMS_ERROR,"空间id不能为空");
        //还要求自己必须在这个空间里面，才能查看
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        SpaceUser spaceUser = spaceUserService.lambdaQuery()
                .eq(SpaceUser::getSpaceId, spaceId)
                .eq(SpaceUser::getUserId, userId)
                .one();
        //如果你不是该空间的，你没有权限访问该空间
        if (spaceUser == null) {
            throw new BusinessException(StateCode.NO_AUTH_ERROR,"空间不存在或无权访问");
        }
        List<SpaceUser> spaceUserList = spaceUserService.list(
                spaceUserService.getQueryWrapper(spaceUserQueryRequest)
        );
        return ResultUtils.success(spaceUserService.getSpaceUserVOList(spaceUserList));
    }

    @PostMapping("/list")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    //必须是超级管理员才能查看任意空间成员的信息
    public BaseResponse<List<SpaceUser>> listSpaceUser(@RequestBody SpaceUserQueryRequest spaceUserQueryRequest) {
        ThrowUtil.throwIf(spaceUserQueryRequest == null, StateCode.PARAMS_ERROR);
        List<SpaceUser> spaceUserList = spaceUserService.list(
                spaceUserService.getQueryWrapper(spaceUserQueryRequest)
        );
        return ResultUtils.success(spaceUserList);
    }

    /**
     * 编辑成员信息（设置权限）
     */
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.SPACE_USER_MANAGE)
    public BaseResponse<Boolean> editSpaceUser(@RequestBody SpaceUserEditRequest spaceUserEditRequest,
                                               HttpServletRequest request) {
        if (spaceUserEditRequest == null || spaceUserEditRequest.getId() <= 0) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        SpaceUser spaceUser = new SpaceUser();
        BeanUtils.copyProperties(spaceUserEditRequest, spaceUser);
        // 数据校验
        spaceUserService.validSpaceUser(spaceUser, false);
        // 判断是否存在
        long id = spaceUserEditRequest.getId();
        SpaceUser oldSpaceUser = spaceUserService.getById(id);
        ThrowUtil.throwIf(oldSpaceUser == null, StateCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = spaceUserService.updateById(spaceUser);
        ThrowUtil.throwIf(!result, StateCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 查询我加入的团队空间列表
     */
    @PostMapping("/list/my")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<SpaceUserVO>> listMyTeamSpace(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        SpaceUserQueryRequest spaceUserQueryRequest = new SpaceUserQueryRequest();
        spaceUserQueryRequest.setUserId(loginUser.getId());
        List<SpaceUser> spaceUserList = spaceUserService.list(
                spaceUserService.getQueryWrapper(spaceUserQueryRequest)
        );
        return ResultUtils.success(spaceUserService.getSpaceUserVOList(spaceUserList));
    }
}
